package com.aiyige.setup.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.aiyige.BuildConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.PreferenceUtil;

import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

public class UpdateSetupService extends IntentService {

    public UpdateSetupService() {
        super("UpdateSetupService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        PreferenceUtil.putLong(SetupUtil.PREF_KEY_LAST_UPDATE_SETUP_TIMESTAMP, System.currentTimeMillis());
        String md5 = SetupUtil.getSetupFileHash();
        if (TextUtils.isEmpty(md5)) {
            md5 = "";
        }

        try {
            Response<ResponseBody> response = ApiManager.getService().setup(BuildConfig.appVersion, md5).execute();
            if (response.code() == ResponseCode.OK) {
                SetupUtil.copySetupFromServer(response);
                SetupUtil.populateSetupList();
            }
        } catch (Exception e) {
            Timber.e("onHandleIntent:" + Log.getStackTraceString(e));
        }
    }

    public static void updateSetup(Context context) {
        context.startService(new Intent(context, UpdateSetupService.class));
    }
}
